package com.molichuxing.framework.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.common.utils.StringUtils;

/**
 * 文件下载工具类
 * 
 * @author zoumingyu
 *
 */
public class DownloadFileUtil {
	private static final Logger logger = LoggerFactory.getLogger(DownloadFileUtil.class);
	/**
	 * 从网络Url中下载文件
	 * 
	 * @param urlStr
	 *            下载路径
	 * @param fileName
	 *            文件名称
	 * @param savePath
	 *            保存路径
	 * @throws IOException
	 */
	public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(5 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		// 获取自己数组
		byte[] getData = readInputStream(inputStream);
		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if (fos != null) {
			fos.close();
		}
		if (inputStream != null) {
			inputStream.close();
		}
		System.out.println("info:" + url + " download success");
	}

	/**
	 * 从输入流中获取字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	// public static void main(String[] args) {
	// try {
	// DownloadFileUtil.downLoadByUrl(
	// "https://m.molichuxing.com/contract/2018/07/214031775008165888/molikejijcd-878d6db601694694b0521802e058275c.pdf",
	// "ELISA.pdf", "D:/tmp/jasmine/invoice");
	// } catch (Exception e) {
	//
	// }
	// }

	/**
	 * 获取网络文件的输入流
	 * @param urlStr
	 * @return
	 */
	public static InputStream getInputStreamByUrl(String urlStr){
		DataInputStream in = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			in = new DataInputStream(conn.getInputStream());
		} catch (IOException e) {
			logger.error("url转换输入流失败,错误信息{}",e);
		}
		return in;
	}

	/**
	 * 导出excel文件
	 * 
	 * @param response
	 * @param fileName
	 * @param xssBook
	 * @throws UnsupportedEncodingException
	 */
	public static void downloadExcel(HttpServletRequest request, HttpServletResponse response, String fileName,
			XSSFWorkbook xssBook) throws UnsupportedEncodingException {
		cors(request, response, fileName);
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			xssBook.write(out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 导出excel文件
	 * 
	 * @param request
	 * @param response
	 * @param fileName
	 * @param sxssBook
	 * @throws UnsupportedEncodingException
	 */
	public static void downloadExcel(HttpServletRequest request, HttpServletResponse response, String fileName,
			SXSSFWorkbook sxssBook) throws UnsupportedEncodingException {
		cors(request, response, fileName);
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			sxssBook.write(out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void cors(HttpServletRequest request, HttpServletResponse response, String fileName)
			throws UnsupportedEncodingException {
		response.reset();
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		if (StringUtils.isBlank(fileName)) {
			response.setHeader("Content-Disposition", "attachment;filename=download");
		} else {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
		}
		// response.setHeader("Access-Control-Allow-Origin","*");
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
	}
}
